import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { inventoryHistory, products } from '@/lib/schema';
import { eq, desc, and, gte, lte } from 'drizzle-orm';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const productId = searchParams.get('productId');
    const startDate = searchParams.get('startDate');
    const endDate = searchParams.get('endDate');
    const type = searchParams.get('type');
    const limit = parseInt(searchParams.get('limit') || '50');

    let query = db
      .select({
        id: inventoryHistory.id,
        type: inventoryHistory.type,
        quantity: inventoryHistory.quantity,
        previousQuantity: inventoryHistory.previousQuantity,
        newQuantity: inventoryHistory.newQuantity,
        notes: inventoryHistory.notes,
        createdBy: inventoryHistory.createdBy,
        createdAt: inventoryHistory.createdAt,
        productName: products.name,
        productSku: products.sku,
      })
      .from(inventoryHistory)
      .leftJoin(products, eq(inventoryHistory.productId, products.id))
      .orderBy(desc(inventoryHistory.createdAt))
      .limit(limit);

    // 添加筛选条件
    if (productId) {
      query = query.where(eq(inventoryHistory.productId, parseInt(productId)));
    }

    if (type) {
      query = query.where(eq(inventoryHistory.type, type));
    }

    if (startDate && endDate) {
      query = query.where(
        and(
          gte(inventoryHistory.createdAt, new Date(startDate).getTime() / 1000),
          lte(inventoryHistory.createdAt, new Date(endDate).getTime() / 1000)
        )
      );
    }

    const history = await query;

    return NextResponse.json(history);
  } catch (error) {
    console.error('获取库存记录失败:', error);
    return NextResponse.json(
      { error: '获取库存记录失败' },
      { status: 500 }
    );
  }
}